#!/bin/bash
clear

#relaunch in Terminal, if double clicked in the Traker
if [ "$1" != "--terminal" ]; then
	#alert --idea "You need to run this from the terminal"
    Terminal -t "Haiku EFI USB Maker II" /bin/bash "$0" --terminal 
    exit 0
fi

#Show a list of drives including the USB drives
mountvolume -l 

#Look for oour special haiku destination partition
DEVICE=$(mountvolume -l | grep -i "haiku-dest" | sed 's/.*(\(.*\))/\1/')
echo "------------------------------------------------------------------------------"

if [ -z "$DEVICE" ]; then
    echo "Temporary HAIKU-DEST volume not found - Process Abandoned!"
    read
    exit 1
fi

echo "Found HAIKU-DEST on device: $DEVICE"

if mount | grep -i -q "/haiku-dest"; then
    echo "Drive is mounted. Unmounting now..."
    unmount -f "/haiku-dest"
fi

echo "We need to initialize with BFS"
if mkfs -t bfs /dev/disk/$DEVICE "Haiku USB Installer"; then
    echo "------------------------------------------------------------------------------"
    echo "Filesystem created successfully. Volume name: HAIKU USB INSTALLER"
else
    echo "------------------------------------------------------------------------------"
    echo "Filesystem creation failed. - Process Abandoned!"
    Read
    exit 1
fi

echo "------------------------------------------------------------------------------"
echo "When using the Haiku Installer, set the destination option..."
echo "                  Onto: [ HAIKU USB INSTALLER     ]"
echo "------------------------------------------------------------------------------"
echo "(about to launch: Haiku Installer...)"
sleep 4

if mount | grep -i -q "/Haiku USB Installer"; then
    echo "Drive is mounted. Unmounting now..."
    unmount -f "/Haiku USB Installer"
fi

/system/apps/Installer &
echo "Installer exited with a status of $?"
read
